package com.credit.mola.app.ui.permission

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.credit.mola.app.R
import com.credit.mola.app.adapter.PermissionListAdapter
import com.credit.mola.app.analysis.CreditMolaSysDataInit
import com.credit.mola.app.databinding.ActivityPremissionListBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.ui.credit.activity.ApplyActivity
import com.credit.mola.app.ui.process.activity.ProcessActivity
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.PermissionReasonDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.helper.SikadwaMainProcessHelper
import com.credit.mola.app.utils.sp.SPUtils
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import com.credit.mola.lib_permission.XXPermissions
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/23 14:26
 * @Annotation：权限列表
 */
class PermissionListActivity: ProActivity() {
    lateinit var binding: ActivityPremissionListBinding

    private var selectedIndex = -1
    private var permissionAdapter: PermissionListAdapter? = null

    //权限处理帮助类
    private var permissionHelper: PermitUtil.PermitHelper? = null
    companion object {
        private const val INTENT_KEY_AMOUNT = "amount"
        private const val INTENT_KEY_UNIT = "unit"
        fun start(context: Context,amount: String, unit: String) {
            val intent = Intent(context, PermissionListActivity::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            intent.putExtra(INTENT_KEY_UNIT,unit)
            context.startActivity(intent)
        }
    }

    override fun getRootView(): View {
        binding = ActivityPremissionListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        binding.permissionContentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initPermissionListView()

        //是否是广告渠道
        val isAdSource = Configs.getSPBoolean(Configs.SPKEY.SIKADWA_IS_ADSOURCE)
        permissionHelper = PermitUtil.PermitHelper(
            activity = this,
            needAllPermit = isAdSource,
            permitUpdateCb = { item ->
                when(item.mark){
                    PermitUtil.PERMIT_MARK_SMS -> {
                        val smsItem = permissionAdapter?.getItem(0)
                        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_SMS)?.let {
                            smsItem?.put("isAgree",it.grant.get())
                        }
                        permissionAdapter?.notifyItemChanged(0)
                    }
                    PermitUtil.PERMIT_MARK_PHONE -> {
                        val smsItem = permissionAdapter?.getItem(2)
                        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_PHONE)?.let {
                            smsItem?.put("isAgree",it.grant.get())
                        }
                        permissionAdapter?.notifyItemChanged(2)
                    }
                    else -> {
                        val smsItem = permissionAdapter?.getItem(1)
                        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_APP)?.let {
                            smsItem?.put("isAgree",it.grant.get())
                        }
                        permissionAdapter?.notifyItemChanged(1)
                    }
                }
                showRequestAgreeAmountInfo()
                showRequestFailureView()
            },
            permitPointCb = { mark,grant ->

            },
            permitFinalPassCb = {
                binding.btnCompleteInformation.isEnabled = true
            },
            permitFinalFailCb = {
                binding.btnCompleteInformation.isEnabled = false
            },
            goSettingCb = { item ->
                XXPermissions.startPermissionActivity(this,item.content)
            })
        if (isAdSource)
            permissionHelper?.watchPermitMark(listOf(PermitUtil.PERMIT_MARK_SMS))

    }

    override fun initListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }

        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Permission Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Permission Page")
        }

        //完成进件信息或申贷
        binding.btnCompleteInformation.setOnClickListener {
            //上报
            CreditMolaSysDataInit.loadDeviceInfoTypeAction()
            if (SikadwaMainProcessHelper.takeSikadwaMainProcessStepList().size > 0){//进件信息未完成
                ProcessActivity.start(this,getLimitAmount())
            } else {
                onIntent(ApplyActivity::class.java)
            }
            finish()
        }
    }

    override fun initData() {
        //进件信息是否完成
        if (SikadwaMainProcessHelper.takeSikadwaMainProcessStepList().size > 0){
            binding.btnCompleteInformation.text = getString(R.string.permission_list_complete_information)
        } else {
            binding.btnCompleteInformation.text = getString(R.string.permission_list_apply_loan)
        }
    }

    override fun onResume() {
        super.onResume()
        if (!isRecreated){//首次创建或只是暂停后恢复
            permissionHelper?.checkWatchPermit()
            loadPermissionDataList()
        } else {
            isRecreated = false
        }
    }

    /**
     * 初始化权限列表
     */
    private fun initPermissionListView(){
//        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        permissionAdapter = PermissionListAdapter(binding.recyclerView)
        binding.recyclerView.adapter = permissionAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        permissionAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            val item =
                permissionAdapter?.getItem(position) ?: return@SikadwaOnItemChildClickListener
            selectedIndex = position
            showCreditMolaPermissionReasonDialog()
        })
    }

    /**
     * 加载权限列表
     */
    private fun loadPermissionDataList(){
        //显示额度 = 额度 / 2
//        val showAmount = BigDecimal(getLimitAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        val showAmount = getLimitAmount()
        val list = arrayListOf<JSONObject>()
        //SMS
        val smsItem = PermHelper.getCreditMolaMESAGItem()
        smsItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.2")).stripTrailingZeros().toPlainString())
        list.add(smsItem)
        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_SMS)?.let {
            smsItem.put("isAgree",it.grant.get())
        }

        //AppList
        val appListItem = PermHelper.getCreditMolaAPListItem()
        appListItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.1")).stripTrailingZeros().toPlainString())
        list.add(appListItem)
        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_APP)?.let {
            appListItem.put("isAgree",it.grant.get())
        }

        //Phone state
        val phoneItem = PermHelper.getCreditMolaPhoneStateItem()
        phoneItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.15")).stripTrailingZeros().toPlainString())
        list.add(phoneItem)
        PermitUtil.gTargetPermitByMark(PermitUtil.PERMIT_MARK_PHONE)?.let {
            phoneItem.put("isAgree",it.grant.get())
        }

        permissionAdapter?.data = list
        showRequestAgreeAmountInfo()
        showRequestFailureView()
        binding.permissionContentLayout.visibility = View.VISIBLE
    }

    /**
     * 显示额度
     */
    @SuppressLint("SetTextI18n")
    private fun showRequestAgreeAmountInfo(){
        //显示额度 = 额度 / 2
        var showAmount = BigDecimal(getLimitAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        var showPassRate = "0"
        permissionAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optInt("isAgree") != 1){
                    continue
                }
                showAmount = BigDecimal(showAmount).add(BigDecimal(item.optString("loanAmount"))).stripTrailingZeros().toPlainString()
                showPassRate = BigDecimal(showPassRate).add(BigDecimal(item.optString("passRate"))).stripTrailingZeros().toPlainString()
            }
        }
        binding.textMaxAmount.text = "$showAmount ${getUnit()}"
        binding.textPassRate.text = "$showPassRate%"
    }

    /**
     * 显示是否存在被拒绝的权限
     */
    private fun showRequestFailureView(){
        var isShowFailure = false
        permissionAdapter?.let {
            for (i in 0..< it.itemCount) {
                val item = it.getItem(i)
                if (item.optInt("isAgree") == -1){
                    isShowFailure = true
                    break
                }
            }
        }
        if (isShowFailure){
            binding.tipsLayout.visibility = View.GONE
            binding.denyLayout.visibility = View.VISIBLE
        } else {
            binding.tipsLayout.visibility = View.VISIBLE
            binding.denyLayout.visibility = View.GONE
        }
    }

    /**
     * 显示权限说明
     */
    private fun showCreditMolaPermissionReasonDialog(){
        val item = permissionAdapter?.getItem(selectedIndex) ?: return
        val requestPermission = item.optString("permission")
        val dialog = PermissionReasonDialog(this,requestPermission,object : PermissionReasonDialog.IDialogCallback{
            override fun onPermissionAgreeClick() {
                addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                when (requestPermission){
                    getString(R.string.permission_app_list_title) -> {
                        permissionHelper?.grantPermit(PermitUtil.PERMIT_MARK_APP)
                    }
                    getString(R.string.permission_device_title) -> {
                        permissionHelper?.grantPermit(PermitUtil.PERMIT_MARK_PHONE)
                    }
                    else -> {
                        permissionHelper?.grantPermit(PermitUtil.PERMIT_MARK_SMS)
                    }
                }
            }

            override fun onPermissionDenyClick() {
                addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_DENY,requestPermission)
                when (requestPermission){
                    getString(R.string.permission_app_list_title) -> {
                        permissionHelper?.denyPermit(PermitUtil.PERMIT_MARK_APP)
                    }
                    getString(R.string.permission_device_title) -> {
                        permissionHelper?.denyPermit(PermitUtil.PERMIT_MARK_PHONE)
                    }
                    else -> {
                        permissionHelper?.denyPermit(PermitUtil.PERMIT_MARK_SMS)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showSikadwaPermissionReason(item)
    }

    /**
     * 获取额度
     */
    private fun getLimitAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 获取单位
     */
    private fun getUnit(): String{
        return intent.extras?.getString(INTENT_KEY_UNIT,"").toString()
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_PERMISSION_START,"")
    }

    override fun onStop() {
        super.onStop()
        PermitUtil.writePermitManager(SPUtils.getAppSp())
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_PERMISSION_END,"")
    }
}